package com.lingtianyu.tech.erbaoshen.core.provider.bean;

import com.lingtianyu.tech.erbaoshen.core.provider.bean.registry.ErBaoShenServiceInstance;
import com.lingtianyu.tech.erbaoshen.core.util.ErBaoShenFinals;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.core.env.Environment;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class ErBaoShenRpcServiceBeans {
    private final Registration registration;
    private final ServiceRegistry serviceRegistry;
    private final Environment env;


    public ErBaoShenRpcServiceBeans(ServiceRegistry serviceRegistry, Registration registration, Environment env) {
        this.serviceRegistry = serviceRegistry;
        this.registration = registration;
        this.env = env;
    }

    private static final Map<String, ServiceBean> serviceBeanMap = new ConcurrentHashMap<>();

    public Map<String, ServiceBean> getServiceBeanMap() {
        return serviceBeanMap;
    }

    public synchronized void putServiceBeanMap(String key, ServiceBean serviceBean, String beanName) {
        serviceBeanMap.put(key, serviceBean);
        String serviceName = key;
        //注册到nacos
        Map<String, String> metadata = registration.getMetadata();
        Map<String, String> newMetadata = new HashMap<>(metadata);
        newMetadata.put(ErBaoShenFinals.FROM_SERVICE, registration.getServiceId());
        int port = registration.getPort();
        if (port <= 0) {
            port = env.getProperty("server.port", int.class);
        }
        String instanceId = serviceName + "-" + registration.getHost() + "-" + port;
        ErBaoShenServiceInstance instance = new ErBaoShenServiceInstance(instanceId, serviceName, registration.getHost(), port, registration.isSecure(), newMetadata);

        serviceRegistry.register(instance);
    }
}
